<template>
  <div style="padding: 20px;">
    <div class="topLocation">今日公告管理 / 今日公告</div>
    <div class="topTool">
      <div class="group">公告相关标题：</div>
      <el-input v-model="searchTitle" placeholder="请输入您想看的公告相关标题" style="margin-right: 50px;"></el-input>
      <div class="group">公告发布日期：</div>
      <el-input v-model="searchPublishtime" placeholder="请输入公告发布日期" style="margin-right: 50px;"></el-input>
      <div class="group">公告内容：</div>
      <el-input v-model="searchContent" placeholder="请输入您想看的公告内容" style="margin-right: 50px;"></el-input>
      <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
      <el-button type="danger" :icon="Delete" @click="handleDelList" v-if="multipleSelection.length > 0">删除选中公告</el-button>
    </div>
    <el-table
        :data="coachData"
        :header-cell-style="{ background: '#f6f9fa'}"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection"/>
      <el-table-column prop="id" label="id" sortable></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="publishtime" label="发布时间" :formatter="formatDate"></el-table-column>
      <el-table-column prop="expirytime" label="结束时间" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        background
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加和编辑公告的表单对话框 -->
    <el-dialog title="公告信息" v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form">
        <el-form-item label="标题">
          <el-input v-model="form.title" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="form.content" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker v-model="form.publishtime" type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="form.expirytime" type="date"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import {ref, onMounted, reactive, computed} from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";

// 响应式变量
const coachData = ref([]);
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const searchTitle = ref('');
const searchPublishtime = ref('');
const searchContent= ref('');

// 日期格式化函数
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '无日期';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return '无效日期';
  }
  return date.toLocaleDateString(); // 使用 toLocaleDateString 格式化日期
};

// 组件挂载时加载数据
onMounted(() => {
  getData();
});

// 获取数据
const getData = () => {
  axios.get('http://localhost:8080/announcement/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchTitle.value,
      publishtime: searchPublishtime.value,
      content: searchContent.value
    }
  })
      .then(response => {
        coachData.value = response.data.data.records;
        total.value = response.data.data.total;
      })
      .catch(error => {
        console.error(error);
      });
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getData();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  getData();
};

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '您确定要删除标题为【' + row.title + '】的公告吗?',
      '危险操作',
  ).then(() => {
    delrow(row.id);
    ElMessage({
      type: 'success',
      message: '完成删除！',
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除!',
    });
  });
};

// 删除请求
const delrow = (id) => {
  axios.delete(`http://localhost:8080/announcement/${id}`)
      .then(response => {
        getData();
      })
      .catch(error => {
        console.error(error);
      });
};

// 查询
const handleSearch = () => {
  const params = {
    title: searchTitle.value || null,
    publishtime: searchPublishtime.value || null,
    content: searchContent.value || null,
  };

  axios.get('http://localhost:8080/announcement/search', { params })
      .then(response => {
        coachData.value = response.data.data;
        total.value = response.data.data.length;
      })
      .catch(error => {
        console.error(error);
        ElMessage.error('查询失败');
      });
};

// 字段排序
const handleSortChange = (sortData) => {
  const { prop, order } = sortData;
  coachData.value = coachData.value.sort((a, b) => {
    if (order === 'ascending') {
      return a[prop] > b[prop] ? 1 : -1;
    } else {
      return a[prop] < b[prop] ? 1 : -1;
    }
  });
};

// 创建响应式变量multipleSelection，用于存储当前选中的数据行
let multipleSelection = ref([]);
// 处理表格行选中状态变化的方法，val是当前选中的数据行数组
const handleSelectionChange = (val) => {
  // 清空数组，确保每次更新都是最新选中状态
  multipleSelection.value = [];
  val.forEach(item => {
    multipleSelection.value.push(item.id); // 将选中的每一行数据的id存入multipleSelection数组中
  });
};

// 批量删除
const handleDelList = () => {
  ElMessageBox.confirm(
      '您确定要删除选择的公告吗?',
      '危险操作',
  ).then(() => {
    const announcementIds = multipleSelection.value;
    axios.delete(`http://localhost:8080/announcement/batch`, { data: announcementIds })
        .then(response => {
          getData();
          ElMessage({ type: 'success', message: '完成批量删除！' });
        })
        .catch(error => {
          console.error('删除失败:', error);
          ElMessage({ type: 'error', message: '删除失败！' });
        });
  }).catch(() => {
    ElMessage({ type: 'info', message: '取消删除!' });
  });
};

// 弹窗相关变量
const dialogVisible = ref(false); // 控制弹窗显示
// 设置弹窗的标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增公告信息' : '编辑公告信息';
});
const form = ref({
  id: '',
  title: '',
  content: '',
  publishtime: '',
  expirytime: ''
});
const dialogType = ref('add'); // 用于区分是添加还是编辑操作

// 处理添加按钮点击事件
const handleAdd = () => {
  dialogVisible.value = true;
  dialogType.value = 'add';
  form.value = {
    id: '',
    title: '',
    content: '',
    publishtime: '',
    expirytime: ''
  };
};

// 确定按钮点击事件处理函数
const handleSave = () => {
  dialogVisible.value = false;
  if (dialogType.value === 'add') {
    addAnnouncement();
  } else {
    updateAnnouncement();
  }
};

// 处理编辑按钮点击事件
const handleEdit = (row) => {
  form.value = { ...row };
  dialogType.value = 'edit';
  dialogVisible.value = true;
};

// 添加公告信息函数
const addAnnouncement = () => {
  const newAnnouncement = { ...form.value };
  axios.post('http://localhost:8080/announcement', newAnnouncement)
      .then(response => {
        ElMessage.success('添加公告信息成功');
        getData(); // 在添加数据后重新获取数据
      })
      .catch(error => {
        ElMessage.error('添加公告信息失败');
        console.error(error);
      });
};

// 更新公告信息
const updateAnnouncement = () => {
  const announcementId = form.value.id;
  const updatedAnnouncement = { ...form.value };
  axios.put(`http://localhost:8080/announcement/${announcementId}`, updatedAnnouncement)
      .then(response => {
        ElMessage.success('修改公告信息成功');
        getData(); // 更新表格显示
      })
      .catch(error => {
        ElMessage.error('修改公告信息失败');
        console.error(error);
      });
};

</script>

<style scoped>
.topLocation {
  font-size: 16px;
  font-weight: bold;
  color: #000; /* 文字颜色为黑色 */
  padding: 10px;
  border-bottom: 2px solid #000; /* 底部边框，黑色 */
  display: flex;
  align-items: center; /* 垂直居中对齐 */
  justify-content: flex-start; /* 左对齐 */
  margin-bottom: 20px; /* 增加距离 */
}

.topTool {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.group {
  white-space: nowrap; /* 防止文字换行 */
  font-size: 14px; /* 设置字体大小为 14px */
}
</style>
